package top.zosoft.server;

import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.*;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zosoft.SimpleHandler;
import top.zosoft.handler.adapter.MqttMessageAdapter;

import java.util.concurrent.TimeUnit;

/**
 * @author neal
 * @date 2023/12/8 17:29
 */
@Component
public class MqttBroker extends Server {

    @Autowired
    private MqttMessageAdapter messageAdapter;
    @Override
    protected AbstractBootstrap initialize() {
        NioEventLoopGroup boss = new NioEventLoopGroup(1,new DefaultThreadFactory(config.name,Thread.MAX_PRIORITY));
        NioEventLoopGroup worker = new NioEventLoopGroup(config.workerCore,new DefaultThreadFactory(config.name,Thread.MAX_PRIORITY));
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss,worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,511)//TODO:这个值需要确定是否合适。
                .childOption(ChannelOption.SO_KEEPALIVE,Boolean.TRUE)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline()
                                .addFirst(new LoggingHandler())
                                .addFirst(new IdleStateHandler(config.readerIdleTime, config.writerIdleTime, config.allIdleTime, TimeUnit.SECONDS))
                                .addLast( new MqttDecoder(1024 * 1024 * 2))
                                .addLast( MqttEncoder.INSTANCE)
                                .addLast(new SimpleHandler());
                             //.addLast(messageAdapter);
                    }
                });
        return  serverBootstrap;
    }
}
